package core;

import org.apache.mina.core.session.IoSession;

import log.ServerLogger;
import util.ServerCache;
import xml.ResponseBody;


/**
 * 
 * @author 胡海亮  QQ:249782944
 * 学校:中南大学 商学院
 * EnterpriseIMServer : 企业即时通讯
 * Apr 26, 2010
 * 
 * IM的服务器类（简单实现版） 注意：此类必须是单例模式
 *      包含  
 *           1: 服务器的配置信息
 *           2：服务器缓存对象（ServerCache）
 *           3：三种Socket
 *           
 *      启动时所需完成的步骤
 *           1：初始化缓存对象
 *           2：初始化服务器数据对象
 *           3：启动服务，在某个端口处监听
 */
public class MinaServer {

	private static MinaServer instance;
	/**服务器化缓存对象	       */
	private ServerCache cache;
	/**聊天消息 ServerSocket	    */
	private MinaSocket minaSocket;
	/**文件消息 ServerSocket     */

	//private EIMServerConfig config;
	/**服务器启动的标志    */
	private boolean isStart=false;

	public static MinaServer getInstance() {
		if(instance==null){
			instance=new MinaServer();
		}
		return instance;
	}

	private MinaServer(){
		initServer();
		isStart=false;
	}

	private void initServer(){
		//config=ServerConfigFactory.createConfig(EIMServerConfig.class);
		cache=ServerCache.getInstance();
		minaSocket=new MinaSocket();
	}

	public boolean startServer(){
		boolean sucess=false;
		if(false==isStart){
			minaSocket.serverStart();
			isStart=true;
			sucess=true;
			ServerLogger.INFO("成功启动服务器");
		}else{
			ServerLogger.INFO("服务器已经启动了，无需再启动");
			sucess=false;
		}
		return sucess;
	}

	public boolean closeServer(){
		boolean sucess=false;
		if(true==isStart){
			minaSocket.closeSocket();
			isStart=false;
			sucess=true;
			ServerLogger.INFO("成功关闭服务器");
		}else{
			ServerLogger.INFO("服务器已经关闭了，无需再关闭");
			sucess=false;
		}
		return sucess;
	}
	public void sendErro(String erro_code,IoSession session) {
		ResponseBody body = new ResponseBody();
		body.setType("erro_response");
		body.setSender("0");
		body.setReciever(Long.toString(session.getId()));
		
		session.write(body);
	}

	public ServerCache getCache() {
		return cache;
	}

	public void setCache(ServerCache cache) {
		this.cache = cache;
	}

	public MinaSocket getChatSocket() {
		return minaSocket;
	}

	public void setChatSocket(MinaSocket minaSocket) {
		this.minaSocket = minaSocket;
	}

	public boolean isStart() {
		return isStart;
	}

	public void setStart(boolean isStart) {
		this.isStart = isStart;
	}

	public void setInstance(MinaServer instance) {
		MinaServer.instance = instance;
	}
	/*
	public EIMServerConfig getConfig() {
		return config;
	}

	public void setConfig(EIMServerConfig config) {
		this.config = config;
	}
	 */


}
